const { getUserId, queryWithBody } = require('../../utils')

const isContentOwner = async (ctx, id, userId) => {
  const exist = await ctx.db.exists.Content({ id, owner: { id: userId } })
  if (!exist) {
    throw new Error('need content owner')
  }
}

const getKeywords = async content => {
  // 请求 keywords 接口
  const keywords = await queryWithBody('keywords', {
    content: content
  })
  let kw = ''
  for (let k in keywords) {
    kw += keywords[k][0] + ','
  }
  console.log('keywords', kw)
  return kw
}

const updatePartName = async (ctx, partId, content) => {
  // 查询 n.parts[0] 符合条件的 contents
  const contents = await ctx.db.query.contents({
    where: {
      parts_some: {
        id: partId
      },
      contentType: 'TEXT'
    }
  })
  let contentsStr = ''
  if (contents && contents.length > 0) {
    contents.forEach(c => {
      contentsStr += c.content + ','
    })
  }
  // 请求 keywords 接口
  const kw = await getKeywords(contentsStr + content)
  // 判断 n.parts[0] 是否有人为修改过
  /* if (n.parts[0].description) {
    data.name = kw
  } */
  await ctx.db.mutation.updatePart({
    where: {
      id: partId
    },
    data: {
      name: kw
    }
  })
}

const content = {
  async createContent (parent, { content, articleIds, location, contentType, styleContent }, ctx, info) {
    const userId = getUserId(ctx)
    // 查询用户写入权限
    // time 是限制时间点
    const beforeTime = new Date()
    // 测试值, 修改为 5 分钟
    beforeTime.setMinutes(beforeTime.getMinutes() - 5)
    // console.log(beforeTime)
    // 添加 Content 到 Part 的时候并不会更新 Part 的 updateAt, 因为是中间表更新的方式
    // 这里使用获取最后一个 Content 为基础
    const articles = await ctx.db.query.articles({
      where: {
        AND: [{
          id_in: articleIds
        }, {
          OR: [{
            owner: {
              id: userId
            }
          },
          {
            cooperations_some: {
              user: {
                id: userId
              }
            }
          }]
        }]
      }
    }, `{
      id
      parts(
        last: 1
      ) {
        id
        name
        description
        contents(
          where: {
            createdAt_gte: "${beforeTime.toISOString()}"
          }
        ) {
          id
          content
          contentType
        }
      }
    }`)
    console.log('查询 articles: ', articles)
    if (!articles || articles.length === 0) {
      return null
    }
    const parts = {
      create: [],
      connect: []
    }
    // forEach 不能使用 async/await
    // await articles.forEach(async n => {
    for (let i = 0; i < articles.length; i++) {
      if (articles[i].parts && articles[i].parts.length === 1 && articles[i].parts[0].contents.length > 0) {
        console.log(articles[i].parts[0].contents)
        // 这里用判断一下如果是文本就请求 wordsvec 接口获取一下数据
        if ((contentType && contentType !== 'TEXT') || articles[i].parts[0].contents[0].contentType !== 'TEXT') {
          await updatePartName(ctx, articles[i].parts[0].id, content)
          parts.connect.push({ id: articles[i].parts[0].id })
        } else {
          const res = await queryWithBody('wordsvec', {
            content: articles[i].parts[0].contents[0].content,
            text: content
          })
          console.log('判断结果', res)
          if (res > 0) {
            await updatePartName(ctx, articles[i].parts[0].id, content)
            parts.connect.push({ id: articles[i].parts[0].id })
          } else {
            // 请求 keywords 接口
            const kw = await getKeywords(content)
            parts.create.push({
              name: kw,
              article: {
                connect: {
                  id: articles[i].id
                }
              }
            })
          }
        }
      } else {
        // 请求 keywords 接口
        const kw = await getKeywords(content)
        parts.create.push({
          name: kw,
          article: {
            connect: {
              id: articles[i].id
            }
          }
        })
      }
    }
    console.log('parts 参数: ', parts)
    // return null
    return ctx.db.mutation.createContent({
      data: {
        content,
        location,
        contentType,
        styleContent,
        author: {
          connect: {
            id: userId
          }
        },
        parts
      }
    }, info)
  },
  async updateContent (parent, { id, content, location, styleContent, disconnectPartId, connectPartId }, ctx, info) {
    const userId = getUserId(ctx)
    await isContentOwner(ctx, id, userId)
    return ctx.db.mutation.updateContent({
      where: {
        id
      },
      data: {
        content,
        location,
        styleContent,
        parts: {
          disconnect: {
            id: disconnectPartId
          },
          connect: {
            id: connectPartId
          }
        }
      }
    }, info)
  },
  async deleteContent (parent, { id }, ctx, info) {
    // 先判断是否有操作权限
    const userId = getUserId(ctx)
    await isContentOwner(ctx, id, userId)
    return ctx.db.mutation.deleteContent({
      where: {
        id
      }
    }, info)
  }
}

module.exports = { content }
